import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { toJS } from 'mobx';
import { withRouter, Route } from 'react-router-dom';
import { Tools, Avatar, Icon, Result, ActionSheet, Toast, Tag, Modal, Bubble } from 'weaver-mobile';
import { RouteLayout, Browser } from 'weaver-mobile-page';
import classnames from 'classnames';
import { renderLoading, getFontColorFromBgHex } from '../../util';

import ContentIframe from './ContentIframe';
import ViewButtons from './ViewButtons';
import Files from './Files';
import ReadList from './ReadList';
import OuterReadList from './OuterReadList';
import { viewTodo } from '../widget/todo/viewTodo';
import SetTodo from '../widget/todo/SetTodo';
import New from '../new/New';
import MoveTo from '../widget/MoveTo';
import FilePreview from '../attachment/filePreview';
import SetTag from '../widget/SetTag';

const { getWeaverFile, getLabel } = Tools;

@inject('viewStore', 'listStore')
@withRouter
@observer
export default class View extends Component {
  static defaultProps = {
    prefixCls: 'email-view',
  }

  constructor(props) {
    super(props);
    this.state = {
      key: '', // 设置代办的key
      file: {}, // 附件预览的file
      isZoom: true, // 是否缩放显示
    }
  }

  componentDidMount() {
    let { params, match: { url, params: { id } }, viewStore: { doInit } } = this.props;
    doInit(url, id, params);

    // 增加邮件查看页面的浏览器缩放支持
    let viewport = document.querySelector("meta[name=viewport]");
    viewport.setAttribute('content', "width=device-width,initial-scale=1,maximum-scale=10,minimum-scale=1,user-scalable=yes");
  }

  componentWillReceiveProps(nextProps) {
    let { viewStore: { doInit, params: { mailId }, setState, hasReceipt, receiptMsgVisible } } = this.props;
    const { match: { url, params: { id }} } = nextProps; 
    if (id && id !== mailId) {
      doInit(url, id);
      // 回执确认 cancalReceipt
      if (receiptMsgVisible && !hasReceipt) {
        this.cancalReceipt(() => setState({hasReceipt: false}))
      }
    }
  }

  componentWillUnmount() {
    const { viewStore: { currentModal, hasReceipt, receiptMsgVisible, clear, params: { readStatus, mailId } }, updateListData } = this.props;

    this.iframState(false)
    clear();

    // 回执确认 cancalReceipt
    if (receiptMsgVisible && !hasReceipt) {
      this.cancalReceipt(() => clear())
    }
    
    ActionSheet.close();
    if (readStatus !== undefined && readStatus === 0) {
      updateListData && updateListData(mailId, { status: 1 });
    }
    // 取消浏览器缩放支持
    let viewport = document.querySelector("meta[name=viewport]");
    viewport.setAttribute('content', "width=device-width,initial-scale=1,maximum-scale=10,minimum-scale=1,user-scalable=no");

    // 弹窗处理
    typeof this.curentModal === 'function' && this.curentModal.close();
    currentModal && typeof currentModal.close === 'function' && currentModal.close()
  }

  onReadedListClick = (id, originalMailId) => {
    const { history, viewStore: { path, doReadInit } } = this.props;
    const params = {
      mailId: id,
      originalMailId,
    };
    doReadInit(params);
    history.push(`${path}/readList`);
  }

  onOuterReadListClick = () => {
    const { history, viewStore: { path, doOuterReadInit } } = this.props;
    doOuterReadInit();
    history.push(`${path}/outerReadList`);
  }

  setStar = (id, star) => {
    const { updateListData, viewStore: { setStar } } = this.props;
    setStar({ mailIds: id, star }, () => updateListData && updateListData(id, { starred: star }));
  }

  emailOcrInvoice = (id,emailOcrInvoiceStatus) => {
    if("1" === emailOcrInvoiceStatus){
      Modal.alert(getLabel('515693','发票识别成功'), '', [
        {text: getLabel('826','确定'),
          onPress: () => { return; }
        },
      ]);
    }else if("0" === emailOcrInvoiceStatus){
      Modal.alert(getLabel('515694','发票识别失败，确定再次识别吗？'), '', [
        {
          text: getLabel('31129','取消'),
          onPress: () => { return; }
        },
        {
          text: getLabel('33703','确认'),
          onPress: () => {
            const { updateListData, viewStore: { emailOcrInvoice } } = this.props;
            emailOcrInvoice({ mailIds: id }, (params) => updateListData && updateListData(id, { emailOcrInvoiceStatus: params.emailOcrInvoiceStatus }));
          }
        },
      ])
    }
  }

  scrollToEnclousure() { // 点击附件滚动到指定位置
    const files = document.getElementById('files');
    const content = document.getElementById('content');
    const offsetTop = files.offsetTop
    content.scrollTop = offsetTop;
  }

  setTodo = (key) => {
    const { history, viewStore: { path } } = this.props;
    if (key !== undefined) { 
      this.setState({ key: key });
    }
    history.push(`${path}/todo`);
  }

  setComplete = () => {
    const { viewStore: { completeWaitdeal, params: { mailId } }, listStore: { updateListData, activeKey } } = this.props;
    completeWaitdeal({ mailIds: mailId }, () => {
      if (activeKey === "doing") { // 待办邮件列表，直接删除
        updateListData(mailId, {}, true);
      } else {
        updateListData(mailId, { mailIds: 0, waitdeal: 0, waitdealBean: {} })
      }
    });
    this.setState({key: ''})
  }

  moveTo = (keys, datas) => {
    if (keys.length === 0) return;
    const { history, updateListData, search, viewStore, listStore: { folderid } } = this.props;
    const { operateUserMailFolder, params: { mailId, activeKey } } = viewStore;
    const needSearchPage = ['star', 'doing', 'tag', 'inner']
    if (folderid && activeKey === "folder" && datas.filter(data => data.id === folderid).length > 0) {
      Toast.info(getLabel(384182, '邮件已经在您要移动的文件夹了，不能重复移动！'));
      return;
    } else if (activeKey && activeKey !== "folder" && datas.filter(data => data.key === activeKey).length > 0) {
      Toast.info(getLabel(384182, '邮件已经在您要移动的文件夹了，不能重复移动！'));
      return;
    }
    operateUserMailFolder({
      operation: 'move',
      mailIds: mailId,
      folderId: keys.join(','),
    }, () => {
      if (needSearchPage.includes(activeKey)) { // 需要更新的列表部分走接口刷新操作
        if (search && typeof search === 'function') search();
      } else {
        updateListData && updateListData(mailId, {}, true);
      }
      history.go(-2);
    });
  }

  todo = (datas) => {
    const { history, updateListData, viewStore: { updateBaseInfo , params: { mailId } } } = this.props;
    const data = {
      waitdeal: 1,
      waitdealBean: { ...datas },
    };
		updateBaseInfo(data);
    updateListData && updateListData(mailId, data);
    history.go(-1);
  }

  // 标记为 
  setTag = (datas, tagList = {}) => {
    const { history, updateListData, viewStore: { markEmailToByMobile, params: { mailId } }, listStore: { activeKey, labelid } } = this.props;
    let updateParams = {};
    let array = datas.map(data => {
      if (data.key === 'markAsStart') {
        updateParams = { ...updateParams, starred: 1 };
      }
      if (data.key === 'markAsCancelStar') {
        updateParams = { ...updateParams, starred: 0 };
      }
      return {
        key: data.key,
        value: data.id,
        mailIds: mailId,
        operation: data.key === 'tagManager' ? 'addLabelByMobile' : '',
      }
    });
    const fiflterData = tagList.groupItems && tagList.groupItems.length > 0 && datas.filter(v => v.key === 'tagManager').length === 0
    if (fiflterData) {
      Modal.alert(getLabel('504597','您的操作会删除所有标签'), getLabel('82017','确认删除？'), [
        {
          text: getLabel('31129','取消'),
          onPress: () => { return; }
        },
        {
          text: getLabel('33703','确认'),
          onPress: () => {
            array = [...array, {
              key: 'clearAll',
              value: '',
              mailIds: mailId,
              operation: 'clearAll',
            }]
            markEmailToByMobile({ markArray: JSON.stringify(array), from: 'view' }, updateParams.starred, (res) => {
              if (res.labels) {
                updateParams = { ...updateParams, labels: res.labels };
              } 
              if (updateListData && typeof updateListData === 'function') {
                if (activeKey === "tag") { // 在标签管理页面才做删除操作
                  updateListData(mailId, {}, true);
                } else {
                  updateListData(mailId, updateParams);
                }
              }
              history.go(-1);
            });
          }
        }
      ])
    } else {
      markEmailToByMobile({ markArray: JSON.stringify(array), from: 'view' }, updateParams.starred, (res) => {
        let presence = [];
        if (res.labels) {
          updateParams = { ...updateParams, labels: res.labels };
          presence = res.labels.filter(v => v.id === labelid);
        } 
        if (updateListData && typeof updateListData === 'function') {
          if (activeKey === "tag" && presence.length === 0) { // 如果在标签列表页面，并且当前标记为标签中不含有当前标签列表id，在该列表将该条目删除
            updateListData(mailId, {}, true);
          } else {
            updateListData(mailId, updateParams);
          }
        }
        history.go(-1);
      });
    }
  }

  doFilePreview = (file) => {
    const { history, viewStore: { path,baseInfo } } = this.props;
    const { prohibitDownload,unPreview } = toJS(baseInfo);
    const isiPhone = Tools.mobileDetect().is('iPhone');
    const isEmobile = Tools.mobileDetect().isEmobile();
    this.setState({ file });
    const { isImg, isCanPreviewForMobile, filelink } = file;
    if("1" == unPreview){
      //禁止预览
      if("1" == prohibitDownload){
        //后台【禁止附件预览】和【禁止移动端下载】同时关闭时，点击附件时需要有提示
        Bubble.warning(getLabel('520701','系统设置原因，该文件只能在PC端下载查看'), 2);
        return;
      }else{
        //下载
        this.curentModal = Modal.alert(getLabel('520702','后台邮件系统设置,禁止附件预览') , getLabel('514233','是否下载？'), [
          { text: getLabel('31129', '取消') },
          { text: getLabel('826', '确定'), onPress: () => {
            if (isiPhone && !isEmobile) {
              window.open(filelink+"&_ec_ismobile=true&ddcode="+file.ddcode);
            } else {
              getWeaverFile(filelink+"&_ec_ismobile=true&ddcode="+file.ddcode, 'iframe','email');
            }
          }},
        ])
      }
    }else{
      if (isImg !== 'true' && isCanPreviewForMobile !== 'true') {
        if("1" == prohibitDownload){
          //若因文件本身的问题不能预览，移动端也不能下载时，点击附件时需要有提示
          Bubble.warning(getLabel('520703','文件格式等原因，该文件只能在PC端下载查看'), 2);
          return;
        }else{
          this.curentModal = Modal.alert(getLabel('514232','当前文件不可预览') , getLabel('514233','是否下载？'), [
            { text: getLabel('31129', '取消') },
            { text: getLabel('826', '确定'), onPress: () => {
              if (isiPhone && !isEmobile) {
                window.open(filelink+"&_ec_ismobile=true&ddcode="+file.ddcode);
              } else {
                getWeaverFile(filelink+"&_ec_ismobile=true&ddcode="+file.ddcode, 'iframe','email');
              }
            }},
          ])
        }
      } else {
        history.push(`${path}/preview`);
      }
    }
  }

  openHrmCard = (id) => {
    if (window.em && (typeof window.em.checkJsApi === 'function') && window.em.checkJsApi('openLink')) {
      window.em.openLink({
        url: `/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`,
        openType: 2,
        sysId: window.localStorage.emobile_ec_id,
      });
    }

   // window.openLink(`/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`);
  }

  // 基本信息
  getBase() {
    const { prefixCls, viewStore: { baseInfo, showAll, setState } } = this.props;
    const userLanguage = window.e9_locale && window.e9_locale.userLanguage || 7;
    const { fromSpan = {}, senddate } = toJS(baseInfo);
    const { imageUrl, showName, hrmId, isInternal } = fromSpan;
    const curCls = classnames(
      `${prefixCls}-base`,
      {['english']: userLanguage === 8}
    )

    let headerProps = {name: showName, url: imageUrl, userId: hrmId};
    return (
      <div className={curCls}>
        {
          isInternal === 1 ?
          <Avatar {...headerProps} />
          : null
        }
        {
          isInternal !== 1 ? 
          <Avatar url={imageUrl} name={showName} />
          : null
        }
        
        <div className={`${prefixCls}-base-right`}>
          <div className={`${prefixCls}-base-right-name`} style={isInternal === 1 ? {color:'#55B1F9'}:{}} onClick={() =>  isInternal === 1 && this.openHrmCard(hrmId)}>
            {showName}
          </div>
          <div className={`${prefixCls}-base-right-date`}>
            <span className='senddate'>{senddate}</span>
            <span className={`${prefixCls}-base-right-reciever`} onClick={() => setState({ showAll: !showAll })}>
              {showAll ?
                <span>{getLabel(83126, '精简信息')}<Icon type="arrow-up-o" size="xxs" /></span> :
                <span>{getLabel(83122, '完整信息')}<Icon type="arrow-down-o" size="xxs" /></span>
              }
            </span>
          </div>
        </div>
      </div>
    );
  }

  // 完整信息
  getComplete() {
    const { prefixCls, viewStore: { baseInfo = {}, showAll } } = this.props;
    const { id, originalMailId, isInternal, toSpan = {}, ccSpan = {}, bccSpan = {}, bccTipInfo, unReadedCount, op_showUnReadedCount, isShowBcc } = toJS(baseInfo);
    return (
      showAll && <div className={`${prefixCls}-complete`}>
        <div className={`${prefixCls}-complete-to`}>
          {toSpan.list && this.getToItem(getLabel(2046, '收件人'), toSpan.list)}
          {ccSpan.list && this.getToItem(getLabel(17051, '抄送人'), ccSpan.list)}
          {isShowBcc === 1 &&
            bccTipInfo ? 
              <div className={`${prefixCls}-complete-to-item`}>
                <span className={`${prefixCls}-complete-to-item-title`}>{getLabel(81316, '密送人')}</span>
                <div className={`${prefixCls}-complete-to-item-detail`}>
                  <span className={`${prefixCls}-base-to-item-detail-tip`}>{bccTipInfo}</span>
                </div>
              </div> :
              bccSpan.list && this.getToItem(getLabel(81316, '密送人'), bccSpan.list)
          }
          {isInternal === 1 ?
            (op_showUnReadedCount === 1 &&
              <div className={`${prefixCls}-complete-unreadedcount`} onClick={() => this.onReadedListClick(id, originalMailId)}>
                {unReadedCount}{getLabel(384293, '个未查看')}
              </div>) : 
            ((true || (this.hasBeyondLen(toSpan.list) || this.hasBeyondLen(ccSpan.list) || this.hasBeyondLen(bccSpan.list))) && 
              <div className={`${prefixCls}-complete-unreadedcount`} onClick={this.onOuterReadListClick}>
                {getLabel(388933, '查看全部')}
              </div>)
          }
        </div>
      </div>
    )
  }

	//外部邮件时，收件人
  hasBeyondLen = (data) => {
    return data && data.length > 5;
  }
 
  getToItem = (name, datas) => { // isShowBcc: 是否邮件的秘送人
    const { prefixCls } = this.props;
    const cls = `${prefixCls}-complete-to-item`;
    if (datas.length === 0) return null;
    const curDatas = datas.length > 5 ? datas.slice(0, 5) : datas;
    return (
      <div className={cls}>
        <span className={`${cls}-title`}>{name}</span>
        <div className={`${cls}-detail`}>
          {curDatas.map((d, index) => (
            <span className={d.readStatus === 0 ? `${cls}-detail-unread`: `${prefixCls}-complete-to-item-detail-readed`} key={`baseTo${index}`}>
              <a className={`${cls}-detail-name`} style={d.isInternal === 1 && d.type ==='resource' ? {color:'#55B1F9'}:{}} onClick={() =>  d && d.isInternal === 1 && d.type ==='resource' && this.openHrmCard(d.typeValue)}>{d.showName}</a>
              {d.op_showReadStatus === 1 && <Icon size="xxs" type={d.readStatus === 0 ? 'mail-small' : 'mail-read'} />}
            </span>
          ))}
          {datas.length > 5 && <span>...</span>}
        </div>
      </div>
    );
  }

  replaceContent = (content) => {
    const res = /<a([\s]+|[\s]+[^<>]+[\s]+)href=(\"([^<>"\']*)\"|\'([^<>"\']*)\')[^<>]*>/gi; // 查找a标签；
    const hrefRes = /href="([^"]*)"/gi;
    let newContent = content;
    newContent = newContent.replace(res, m => {
      if (m.indexOf('common/chatResource/emailURL.html') !== -1) {
        return m.replace(hrefRes, n => `${n.slice(0,n.length-1)}&em_client_type=mobile"`)
      } else {
        return m
      }
    })
    return newContent;
  }

  // 切换视图
  changeViewer = (bool) => {
    let isZoom = bool || !this.state.isZoom
    // 滚动还原
    if (isZoom) {
      const iframe = document.getElementsByClassName('email-view-content-iframecontainer')
      const content = iframe && iframe[0]
      if (content) {
        content.scrollLeft = 0
        this.setState({ isZoom });
      }
    } else {
      this.setState({ isZoom });
    }
  }

  // 内容 （滚动区域）
  getContent() {
    let { prefixCls, viewStore: { baseInfo, content, iframeLoading, iframContentLoading, iframContent } } = this.props;
    const { id, fileInfos = {}, subject, labels, waitdeal, starred, waitdealBean, isSender, recallstate, belongtoType, classification, classificationSpan,emailOcrInvoiceStatus, texttype } = toJS(baseInfo);
    const { count } = fileInfos;
    content = content && this.replaceContent(content);
    return (
      <div className={`${prefixCls}-content`}>
        {iframeLoading && Toast.loading('',0)}
        {isSender === 0 && belongtoType =="" && recallstate === 1 ? 
          <div className={`email-noright ${prefixCls}-withdraw`}>
            <Result
              img={<Icon type="mail-withdrawal-of-mail" />}
              message={getLabel(32063, '发信方已撤回邮件')}
            />
          </div> :
          <div className={`${prefixCls}-content-flex`} id="content">
            {this.getComplete()}
            <div className={`${prefixCls}-content-container`}>
              <div className={`${prefixCls}-content-title`}>
                <span className={`${prefixCls}-content-title-subject`} dangerouslySetInnerHTML={{ __html: subject }}></span>
                {count > 0 && <span className={`${prefixCls}-content-title-icon`} onClick={this.scrollToEnclousure}><Icon type="enclosure" size="xxs" /></span>}
                {<span className={`${prefixCls}-content-title-icon`} onClick={() => this.setStar(id, starred === 1 ? 0 : 1)}>
                  {starred === 1 ? <Icon type="blog-xing" size="xxs" /> : <Icon type="collection" size="xxs" />}
                  </span>
                }
                {emailOcrInvoiceStatus && <span className={`${prefixCls}-content-title-icon`} onClick={() => this.emailOcrInvoice(id,emailOcrInvoiceStatus)}>
                  {emailOcrInvoiceStatus === "1" ? <Icon color={"#1BDD3F"} type="finance-right" size="xxs" /> : <Icon color={"#F72B2B"} type="finance-wrong" size="xxs" />}
                  </span>
                }
                {
                  (belongtoType === '1' || belongtoType === '2') && (
                    <span className={`${prefixCls}-content-title-icon account-type`}>
                      {
                        belongtoType === '1' ? <Icon type="zhuzhanghao" size="xs"/> : 
                        belongtoType === '2' ? <Icon type="cizhanghao" size="xs"/> :
                        ''
                      }
                    </span>
                  )
                }
                {
                  Number(texttype) !== 1 && (
                    <span className={`${prefixCls}-content-title-icon ${!this.state.isZoom && 'isZoom'}`} onClick={() =>this.changeViewer()}>
                      <Icon type='email-switch' size="xxs" />
                    </span>
                  )
                }
              </div>
              {labels && labels.length > 0 &&
                <div className="email-list-list-item-tags">
                  {
                    labels.map(({ color, name, id: tagId }) => (
                      <Tag key={tagId} style={{ color: getFontColorFromBgHex(color),background: color }}>
                        {name}
                      </Tag>
                    ))
                  }
                </div>
              }
              {waitdeal === 1 && <div className={`${prefixCls}-content-date`} onClick={() => {viewTodo(waitdealBean, this.setTodo, this.setComplete)}}>
                <Icon type="blog-bujiao" size="xxs" />
                {waitdealBean.waitdealtime}
              </div>}
              {
                classification && classificationSpan && (
                  <div className={`${prefixCls}-content-secrecy`}>{getLabel('515181','密级：')}{classificationSpan}</div>
                )
              }
            </div>
            {
              Number(texttype) === 1 ? (
                <div className={`${prefixCls}-content-emailcontainer`} dangerouslySetInnerHTML={{ __html: content }} />
              ) : (
                <ContentIframe ref='content' value={content} isZoom={this.state.isZoom} fun={this.iframState} contentLoading={iframContentLoading} imgReg={iframContent} changeZoom={this.changeViewer}/>
              )
            }
            <div id="files">
              <Files doFilePreview={this.doFilePreview} />
            </div>
          </div>
        }
      </div>
    )
  }

  iframState = (val) => {
    const { viewStore: { setState } } = this.props;
    setState({iframeLoading: val})
    !val && Toast.hide();
  }

  // 回执取消
  cancalReceipt = (callback) => {
    const { viewStore } = this.props;
    const { params: { mailId }, setState, getReceiptMsg } = viewStore;
    getReceiptMsg({mailId, operateType: 'readReceipt'});
    setState({ receiptMsgVisible: false });
    if (callback) callback();
  }

  // 删除|永久删除
  deleteCallBack = (type, mailId) => {
    const { params, search, updateListData } = this.props;
    const needSearchPage = ['star', 'doing', 'tag', 'inner']
    // 说明是从邮件模块内部列表打开的详情
    if (params && params.activeKey && needSearchPage.includes(params.activeKey) && type !== 'remove') { // 需要更新的列表部分走接口刷新操作
      if (search && typeof search === 'function') search();
    } else {
      updateListData && updateListData(mailId, {}, true)
    }
  }

  render() {
    const { prefixCls, viewStore, updateListData } = this.props;
    const { path, rightLoading, baseLoading, right, secrecyRight, baseInfo = {}, crmContactRecord, docs, cusBrowser, docBrowser, newParams, params: { mailId }, buttons, receiptMsgVisible, setState, getReceiptMsg } = viewStore;
    const { isSender, recallstate, waitdeal, waitdealBean,belongtoType, fileInfos } = toJS(baseInfo);
    const cls = classnames('wm-route-layout', prefixCls);
    let child = null;

    let todoParams = { key: this.state.key, mailId };
    if (waitdeal === 1) {
      todoParams = { ...todoParams, formParams: { ...waitdealBean } };
    }
    if (rightLoading || baseLoading) {
      child = renderLoading;
    } else if (right !== 1) {
      if(right  === -1){
        child =  (
          <div className="email-noright">
            <Result
              img={<Icon type="wuquanxian" />}
              message={getLabel(390255, '该邮件已被删除')}
            />
          </div>
        );
      } else {
        child = (
          <div className="email-noright">
            <Result
              img={<Icon type="wuquanxian" />}
              message={getLabel(385529, '无权查看该邮件')}
            />
          </div>
        );
      }
    } else if (right === 1 && secrecyRight !== 1) {
      child =  (
        <div className="email-noright">
          <Result
            img={<Icon type="wuquanxian" />}
            message={'对不起，您的人员密集不足以查看该内容'}
          />
        </div>
      );
    } else {
      child = (
        <div className={`${prefixCls}-box`}>
          {(isSender === 1 || belongtoType !="") && recallstate === 1 && <div className={`${prefixCls}-top`}>{getLabel(384304, '已撤回邮件')}</div>}
          <div className={`${prefixCls}-container`}>
            <div className={`${prefixCls}-flex`}>
              <Modal
                title={getLabel(32473, '发件人希望得到您的回执，是否发送？')}
                visible={receiptMsgVisible}
                transparent
                footer={[
                  { text: getLabel('31129', '取消'), onPress: () => this.cancalReceipt() },
                  { text: getLabel('826', '确定'), onPress: () => {
                    getReceiptMsg({mailId, operateType: 'receiveNeedReceipt'})
                    setState({ receiptMsgVisible: false });
                  }}
                ]}
              />
              {this.getBase()}
              {this.getContent()}
            </div>
          </div>
          <ViewButtons 
            data={toJS(buttons)} 
            updateListData={updateListData} 
            delCallBack={this.deleteCallBack} 
            from={this.props.from} 
            needRefresh={fileInfos && fileInfos.count > 1} 
            refreshList={this.props.refreshList}
          />
          <div style={{ display: 'none '}}>
            <Browser  
              store={cusBrowser}
              type={7}
              isSingle
              onChange={value => {
                if (value !== '') {
                  crmContactRecord({ mailIds: mailId, crmIds: value });
                }else{
                  Toast.info(getLabel('516962', '请选择客户'), 1);
                  return;
                }
              }}
              valueArray={[]}
            />
            <Browser  
              store={docBrowser}
              type={'doccategory'}
              dataParams={{ iscreate: 1 }}
              isSingle
              onChange={value => {
                if (value !== '') {
                  docs({ mailIds: mailId, secId: value });
                }else{
                  Toast.info(getLabel('516961', '请选择目录'), 1);
                  return;
                }
              }}
              valueArray={[]}
            />
          </div>
          <Route
            key="filePreview"
            path={`${path}/preview`}
            render={() => (<FilePreview path={`${path}/preview`} file={this.state.file} />)}
          />
          <Route
            key="readList"
            path={`${path}/readList`}
            render={() => {
              return (
                <ReadList path={`${path}/readList`} openHrmCard={datas => this.openHrmCard(datas)}/>
              );
            }}
          />
          <Route
            key="outerReadList"
            path={`${path}/outerReadList`}
            render={() => {
              return (
                <OuterReadList path={`${path}/outerReadList`} />
              );
            }}
          />
          <Route
            key="new"
            path={`${path}/new`}
            render={() => {
              return (
                <New path={`${path}/new`} params={toJS(newParams)}/>
              );
            }}
          />
          <Route
            key="todo"
            path={`${path}/todo`}
            render={() => {
              return (
                <SetTodo path={`${path}/todo`} params={todoParams} onSubmit={datas => this.todo(datas)} />
              );
            }}
          />
          <Route
            key="moveTo"
            path={`${path}/moveTo`}
            render={() => {
              return (
                <MoveTo path={`${path}/moveTo`} params={{ from: 'view', mailId, isBatch: 0 }} onSubmit={this.moveTo} />
              );
            }}
          />
          <Route
            key="setTag"
            path={`${path}/setTag`}
            render={() => {
              return (
                <SetTag path={`${path}/setTag`} params={{ from: 'view', mailId, isBatch: 0 }} onSubmit={this.setTag} />
              );
            }}
          />
        </div>
      );
    }

    return (
      <RouteLayout>
        <div key="view" className={cls}>{child}</div>
      </RouteLayout>
    );
  }
}